如果對 DI 有些了解的人大概都碰過,不管是使用 Dagger 還是 Koin,今天就要來介紹 Hilt,以下如有解釋不清或是描述錯誤的地方還請大家多多指教:
介紹 hilt 之前要先了解一下什麼是 DI,DI 也就是 Dependency Injection,將要使用的物件透過外部注入的方式給另一個 class 做使用,避免在 class 中直接 new 物件,這樣有什麼好處呢?
而 Hilt 是以 Dagger 為基礎的 DI 框架,它透過 anotention 簡化了 Dagger 的 Component 的實作,原先需手動建立的檔案由 Hilt 產生。
Android Studio 版本要 Arctic Fox or higher
project 的 build.gradle 設置 dependency
buildscript {
    ...
    ext.hilt_version = '2.41'
    dependencies {
        ...
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
    }
}
module 的 build.gradle
apply plugin: 'dagger.hilt.android.plugin'
...
dependencies {
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
}
anotention 自己建立的 application class
@HiltAndroidApp
class WeathApplication : Application() {
    companion object {
        var instance: WeathApplication by Delegates.notNull()
    }
    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
	...
}
Warning:
Hilt does not support retained fragments.
@HiltViewModel
class MainViewModel: ViewModel()
db 透過 inject 的方式帶入 viewModel :
@HiltViewModel
class MainViewModel @Inject constructor(
    private val db: CityDAO,
	private val api: WeathbyService
): ViewModel()
為 db 建立 Module,透過 Module 來跟 hilt 做綁定
@InstallIn(SingletonComponent::class)
@Module
object DatabaseModule {
    @Singleton
    @Provides
    fun provideDB(app: Application): CityDatabase = CityDatabase.getInstance(app)
    @Singleton
    @Provides
    fun provideCityDao(db: CityDatabase): CityDAO = db.cityDao()
}
API 的部分稍微修改了原本的寫法:
object WeathbyRetrofit {
   ...
    // origin
    fun makeRetrofitService(): WeathbyService {
        return Retrofit.Builder()
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .baseUrl(BASE_URL)
            .client(client)
            .build().create(WeathbyService::class.java)
    }
	// edit
    fun makeRetrofitService(): Retrofit {
        return Retrofit.Builder()
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .baseUrl(BASE_URL)
            .client(client)
            .build()
    }
}
@InstallIn(SingletonComponent::class)
@Module
object NetworkModule {
    @Singleton
    @Provides
    fun provideApi(): WeathbyService {
        return WeathbyRetrofit
            .makeRetrofitService()
            .create(WeathbyService::class.java)
    }
}
rebuild 完可以正常運行就成功了優